import { mapDisplayNameToTableName, mapMultipleDisplayNames } from '../lib/dynamic-table-mapping';
import { getDeviceParameterDb } from '../lib/device-parameter-database';

/**
 * 使用动态表名映射重构设备映射修正功能
 * 替代硬编码的映射表
 */
async function refactorDeviceMappingsWithDynamicMapping() {
  try {
    const db = getDeviceParameterDb();
    const deviceParameterDb = db as any;

    console.log('🔄 使用动态映射修正设备类型映射表...');
    console.log('✅ 不再需要维护硬编码映射表！');

    // 获取所有映射记录
    const mappingsQuery = `
      SELECT id, classification_code, naming_table, position_table, base_params_table
      FROM device_type_mappings
    `;

    const mappings = deviceParameterDb.db.prepare(mappingsQuery).all();
    console.log(`📋 找到 ${mappings.length} 个设备类型映射`);

    // 更新映射表
    const updateMappingStmt = deviceParameterDb.db.prepare(`
      UPDATE device_type_mappings 
      SET 
        naming_table = ?,
        position_table = ?,
        base_params_table = ?,
        updated_at = datetime('now')
      WHERE id = ?
    `);

    let updatedCount = 0;
    let skippedCount = 0;
    
    for (const mapping of mappings) {
      // 使用动态映射转换显示名称到实际表名
      const actualNamingTable = mapDisplayNameToTableName(mapping.naming_table);
      const actualPositionTable = mapDisplayNameToTableName(mapping.position_table);
      const actualBaseParamsTable = mapDisplayNameToTableName(mapping.base_params_table);
      
      // 只有当至少有一个表名需要更新时才执行更新
      if (actualNamingTable !== mapping.naming_table || 
          actualPositionTable !== mapping.position_table || 
          actualBaseParamsTable !== mapping.base_params_table) {
        
        try {
          updateMappingStmt.run(
            actualNamingTable,
            actualPositionTable,
            actualBaseParamsTable,
            mapping.id
          );
          
          console.log(`✅ 修正: ${mapping.classification_code}`);
          if (actualNamingTable !== mapping.naming_table) {
            console.log(`   命名表: ${mapping.naming_table} -> ${actualNamingTable}`);
          }
          if (actualPositionTable !== mapping.position_table) {
            console.log(`   位置表: ${mapping.position_table} -> ${actualPositionTable}`);
          }
          if (actualBaseParamsTable !== mapping.base_params_table) {
            console.log(`   参数表: ${mapping.base_params_table} -> ${actualBaseParamsTable}`);
          }
          
          updatedCount++;
        } catch (error) {
          console.error(`❌ 修正映射失败 ${mapping.classification_code}:`, error);
        }
      } else {
        skippedCount++;
      }
    }

    console.log(`\n📊 修正结果:`);
    console.log(`   ✅ 成功修正: ${updatedCount} 个映射`);
    console.log(`   ⏩ 无需修正: ${skippedCount} 个映射`);
    console.log(`   🎯 总计处理: ${mappings.length} 个映射`);

    // 验证修正结果
    const verifyStmt = deviceParameterDb.db.prepare(`
      SELECT classification_code, naming_table, position_table, base_params_table
      FROM device_type_mappings
      WHERE naming_table LIKE '表%' OR position_table LIKE '表%' OR base_params_table LIKE '表%'
      LIMIT 5
    `);
    const remainingIssues = verifyStmt.all();
    
    if (remainingIssues.length > 0) {
      console.log('\n⚠️ 还有以下映射使用显示名称:');
      remainingIssues.forEach((issue: any) => {
        console.log(`   ${issue.classification_code}: ${issue.naming_table}, ${issue.position_table}, ${issue.base_params_table}`);
      });
      console.log('💡 这可能表示动态映射需要增强以覆盖更多显示名称变体');
    } else {
      console.log('\n✅ 所有映射都已使用实际表名，映射修正完成！');
    }

  } catch (error) {
    console.error('❌ 动态映射修正失败:', error);
    process.exit(1);
  }
}

/**
 * 演示批量名称转换的高效用法
 */
function demonstrateBatchConversion() {
  console.log('\n💡 批量转换演示:');
  
  // 模拟从设备数据中获取的表名
  const deviceTableNames = {
    naming: '表 C.2',
    position: '表C.4', 
    baseParams: '表 C.109-1',
    techSpec: '表 C.144'
  };
  
  console.log('📥 输入的显示名称:');
  Object.entries(deviceTableNames).forEach(([key, name]) => {
    console.log(`   ${key}: "${name}"`);
  });
  
  // 使用批量转换（推荐方式）
  const convertedNames = mapMultipleDisplayNames(deviceTableNames);
  
  console.log('📤 转换后的表名:');
  Object.entries(convertedNames).forEach(([key, name]) => {
    console.log(`   ${key}: "${name}"`);
  });
  
  console.log('\n💰 批量转换的优势:');
  console.log('   - 一次性转换多个名称，减少数据库查询');
  console.log('   - 利用缓存机制，提高性能');
  console.log('   - 代码更简洁，减少重复调用');
}

/**
 * 生成重构建议和代码样例
 */
function generateRefactoringGuide() {
  console.log('\n📝 重构指南:');
  console.log('================');
  
  console.log('\n1. 🔄 替换硬编码映射对象:');
  console.log('   替换前:');
  console.log('   ```typescript');
  console.log('   const hardcodedMapping = {');
  console.log('     "表 C.2": "table_c2",');
  console.log('     "表C.2": "table_c2",');
  console.log('     // ... 更多映射');
  console.log('   };');
  console.log('   const tableName = hardcodedMapping[displayName] || displayName;');
  console.log('   ```');
  
  console.log('\n   替换后:');
  console.log('   ```typescript');
  console.log('   import { mapDisplayNameToTableName } from "../lib/dynamic-table-mapping";');
  console.log('   const tableName = mapDisplayNameToTableName(displayName);');
  console.log('   ```');
  
  console.log('\n2. ⚡ 批量转换优化:');
  console.log('   替换前:');
  console.log('   ```typescript');
  console.log('   const naming = hardcodedMapping[device.naming_table] || device.naming_table;');
  console.log('   const position = hardcodedMapping[device.position_table] || device.position_table;');
  console.log('   const baseParams = hardcodedMapping[device.base_params_table] || device.base_params_table;');
  console.log('   ```');
  
  console.log('\n   替换后:');
  console.log('   ```typescript');
  console.log('   import { mapMultipleDisplayNames } from "../lib/dynamic-table-mapping";');
  console.log('   const tableNames = mapMultipleDisplayNames({');
  console.log('     naming: device.naming_table,');
  console.log('     position: device.position_table,');
  console.log('     baseParams: device.base_params_table');
  console.log('   });');
  console.log('   ```');
  
  console.log('\n3. 🏗️ 需要修改的文件:');
  const filesToRefactor = [
    'scripts/fix-device-mappings-to-real-tables.ts',
    'scripts/fix-device-mappings-from-original.ts',
    '其他使用硬编码映射的文件'
  ];
  
  filesToRefactor.forEach(file => {
    console.log(`   - ${file}`);
  });
  
  console.log('\n4. ✅ 重构收益:');
  console.log('   - 消除维护硬编码映射的负担');
  console.log('   - 新增表时自动支持，无需修改代码');
  console.log('   - 动态从数据库元数据生成，保证一致性');
  console.log('   - 支持缓存，性能优于查表方式');
  console.log('   - 减少代码体积和复杂度');
}

async function main() {
  console.log('🚀 开始动态映射重构演示...\n');
  
  // 1. 执行动态映射修正
  await refactorDeviceMappingsWithDynamicMapping();
  
  // 2. 演示批量转换
  demonstrateBatchConversion();
  
  // 3. 生成重构指南
  generateRefactoringGuide();
  
  console.log('\n🎉 动态映射重构演示完成！');
  console.log('💡 建议按照重构指南逐步替换项目中的硬编码映射。');
}

// 如果直接运行此脚本
if (require.main === module) {
  main();
}